# 作者: YYJ
# 2025年07月08日13时22分46秒
# 2486249622@qq.com

import socket
import sys

import select

class ChatClient:
    def __init__(self, host, port):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect((host, port))
        self.epoll = select.epoll()
        self.running = True

    def run(self):
        self.epoll.register(self.client.fileno(), select.EPOLLIN)
        self.epoll.register(sys.stdin.fileno(), select.EPOLLIN)
        try:
            while self.running:
                events = self.epoll.poll(-1)
                for fd, event in events:
                    if fd == self.client.fileno():  # 服务器发来数据
                        if event & select.EPOLLIN:
                            data = self.client.recv(1024).decode('utf-8').strip()
                            if data:
                                print(data)
                            else:
                                print('Server closed')
                                self.running = False
                                break
                    elif fd == sys.stdin.fileno() and event & select.EPOLLIN:  # 客户端发出数据，写到连接里
                        msg = sys.stdin.readline().strip()
                        if msg:
                            self.client.sendall(msg.encode('utf-8'))
        finally:
            self.epoll.unregister(self.client.fileno())
            self.epoll.unregister(sys.stdin.fileno())
            self.epoll.close()
            self.client.close()

if __name__ == '__main__':
    client = ChatClient('127.0.0.1', 8000)
    client.run()